const mysql = require('mysql2/promise'),
      log   = console.log,
      Koa   = require('koa'),
      app   = new Koa(),
      Router = require('koa-router'),
      router = new Router(),
      bodyparser = require('koa-bodyparser'),
      fs    = require('fs'),
      path  = require('path'),
      cors  = require('koa2-cors'),
      http  = require('http'),
      https = require('https'),
      hq = require('./shouye.js');

app.use(bodyparser());

const options = {
    key:fs.readFileSync(path.join(__dirname,'./fourgoldhua.cn.key')),
    cert:fs.readFileSync(path.join(__dirname,'./fourgoldhua.cn.crt'))
}

app.use(cors({
    origin: function (ctx) {
        if (ctx.url === '/shouye' || ctx.url === '/yonghu' || ctx.url ==='/shenhe?judge=1' || ctx.url === '/shenhe?judge=0' 
          || ctx.url === '/xiangqing' || ctx.url ==='/shenhezhong' || ctx.url ==='/shop' || ctx.url === '/shop/sousuo'
          || ctx.url === '/pinglun' || ctx.url === '/delpinglun' || ctx.url === '/shouye/shuju' || ctx.url === '/shenhe?judge=2') {
          return "*"; // 允许来自所有域名请求
        }
        return 'http://localhost:8080'; // 这样就能只允许 http://localhost:8080 这个域名的请求了
    },
    exposeHeaders: ['WWW-Authenticate', 'Server-Authorization'],
    maxAge: 5,
    credentials: true,
    allowMethods: ['GET', 'POST', 'DELETE'],
    allowHeaders: ['Content-Type', 'Authorization', 'Accept'],
}))


function climg (obj, fn) {
  for (var i in obj) {
      if (typeof obj[i] === 'object') {
            climg(obj[i], fn)
          }
    if (fn(obj[i])) {
          delete obj[i]
        }
  }
}
 
function delimg (foo) {
    if (typeof foo === 'object') {
          for (var i in foo) {
                  return false
                }
          return true
        } else {
              return foo === '' || foo === null || foo === undefined
            }
}


function forDate(now) {
  var date = new Date(now /1000 * 1000);
  //log(date);
  var year=date.getFullYear();  //取得4位数的年份
  var month=date.getMonth()+1;  //取得日期中的月份，其中0表示1月，11表示12月
  var date1=date.getDate();      //返回日期月份中的天数（1到31）
  var hour=date.getHours();     //返回日期中的小时数（0到23）
  var minute=date.getMinutes(); //返回日期中的分钟数（0到59）
  var second=date.getSeconds(); //返回日期中的秒数（0到59）
  return year+"-"+month+"-"+date1+" "+hour+":"+minute+":"+second;
}


//首页信息
router.get('/shouye/shuju',async (ctx)=>{
  let arr = await hq.getshouye();
  fabu = arr[0].share_id;
  tongguo = arr.length;
  weitongguo = arr[0].share_id-arr.length;
  let brr = await hq.getshouyenum();
  usernum = brr.length;
  let crr=[];
  crr.push({
    "fabu":fabu,
    "tongguo":tongguo,
    "weitongguo":weitongguo,
    "usernum":usernum
  })
  ctx.body = JSON.stringify(crr);
})
//用户信息
router.get('/yonghu',async (ctx)=>{
  let {user_id} = ctx.request.query;
  //let user_id = ctx.request.body.user_id;
  let arr;
  if (user_id!=null){
    arr = await hq.getxinxi(user_id);
  }
  else
    arr = await hq.getxinxi1();
  let brr=[];
  for(let i=0;i<arr.length;i++){
    let id = arr[i].id;
    let brr1 = await hq.getshopnum(id);
    let brr2 = await hq.getdavnum(id);
    let brr3 = await hq.getfensinum(id);
    brr.push({
      "user_id":id,
      "user_name":arr[i].user_name,
      "user_img":arr[i].user_img,
      "shopnum":brr1.length,
      "davnum":brr2.length,
      "fensinum":brr3.length
    })
  }
  log(brr);
  ctx.body = JSON.stringify(brr);
})
//分享审核分类
router.get('/shenhe',async (ctx)=>{
  let {judge} = ctx.request.query;
  //let judge = ctx.request.body.judge;
  let arr = await hq.getshenhe(judge);
  ctx.body = JSON.stringify(arr);
})
//分享详情
router.post('/xiangqing',async (ctx)=>{
  let share_id = ctx.request.body.id;
  //let {share_id} = ctx.request.query;
  let arr = await hq.getid_home(share_id);
  climg(arr,delimg);
  //log(arr);
  ctx.body = JSON.stringify(arr);
})
//审核
router.post('/shenhezhong',async (ctx)=>{
  //let {share_id,judge} = ctx.request.query;
  let share_id = ctx.request.body.share_id;
  let judge = ctx.request.body.judge;
  await hq.getshenhezhong(share_id,judge);
  ctx.body = JSON.stringify('成功啦啦啦啦啦');
})
//商家信息
router.get('/shop',async (ctx)=>{
  let arr = await hq.getshop();
  ctx.body = JSON.stringify(arr);
})
//商家模糊搜索
router.post('/shop/sousuo',async (ctx)=>{
  //let {text} = ctx.request.query;
  let text = ctx.request.body.text;
  let arr = await hq.getss(text);
  log(arr);
  ctx.body = JSON.stringify(arr);
})
router.get('/shop/state',async (ctx)=>{
  let {state} = ctx.request.query;
  let arr = await hq.getshop1(state);
  log(arr)
  ctx.body = JSON.stringify(arr);  
})
//审核
router.get('/shop/shenhe',async (ctx)=>{
  let {id,state} = ctx.request.query;
  await hq.getshopsh(id,state);
  let arr = await hq.getshop2(id)
  ctx.body = JSON.stringify(arr);
})
//详情页 搜索
router.post('/xiangqing/sousuo',async (ctx)=>{
  //let {id,text} = ctx.request.query;
  let id = ctx.request.body.id;
  let text = ctx.request.body.text;
  let arr = await hq.getxqss(id,text);
  log(arr);
  ctx.body = JSON.stringify(arr);
})
//评论区展示
router.get('/pinglun',async (ctx)=>{
  let arr = await hq.getpl();
  log(arr);
  let brr = [];
  var time;
  for(let i = 0 ;i < arr.length ; i++){
    let crr = await hq.getname(arr[i].user_id);
    time = forDate(arr[i].date);
    brr.push({
      "id":arr[i].id,
      "share_id":arr[i].share_id,
      "user_id":arr[i].user_id,
      "user_name":crr[0].user_name,
      "date":time,
      "text":arr[i].text,
      "zan":arr[i].zan,
      "state":arr[i].state
    })
  }
  log(brr);
  ctx.body = JSON.stringify(brr);
})
//删除评论
router.post('/delpinglun',async (ctx)=>{
  let id = ctx.request.body.id;
  console.log(id);
  await hq.delpl(id);
  let arr = await hq.getpl1();
  for(let i = 0;i<arr.length;i++){
    arr[i].date = forDate(arr[i].date);
  }
  ctx.body = JSON.stringify(arr);
})
//查看评论
router.get('/pinglun/text',async (ctx)=>{
  let {text} = ctx.request.query;
  let arr = await hq.gettext(text);
  let brr = [];
  var time;
  for(let i = 0 ;i < arr.length ; i++){
      let crr = await hq.getname(arr[i].user_id);
      time = forDate(arr[i].date);
      brr.push({
            "id":arr[i].id,
            "share_id":arr[i].share_id,
            "user_id":arr[i].user_id,
            "user_name":crr[0].user_name,
            "date":time,
              "text":arr[i].text,
            "zan":arr[i].zan,
            "state":arr[i].state
          })
  }
  log(brr);
  ctx.body = JSON.stringify(brr);
})
//商家入驻
/*
rokill -9 uter.get('/shop/insert'async (ctx)=>{
  let {id, shop_name, shop_tel, shop_addr, shop_jwd, sshop_mtid, shop_starcount, shop_count, shop_distribution1, shop_distribution2, shop_label, shop_reduction1, shop_reduction2, shop_reduction3, shop_announcementinfo}
})*/
process.on('unhandledRejection',(reason,p) => {
    console.log('Unhandled Rejection at:Promise',p,'reason:',reason);
});
app.use(router.routes())
   .use(router.allowedMethods());

//app.listen(2000);
https.createServer(options,app.callback()).listen(2000);

